jQuery(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */

    jQuery('.numbersOnly').keyup(function () {
        this.value = this.value.replace(/[^0-9\.]/g,'');
    });

	var tmp;
	
	jQuery('.note').each(function(){
		/* Finding the biggest z-index value of the notes */
		tmp = jQuery(this).css('z-index');
		if(tmp>zIndex) zIndex = tmp;
	})

	/* A helper function for converting a set of elements to draggables: */
	make_draggable(jQuery('.note'));

    jQuery( "#noteDialog:ui-dialog" ).dialog( "destroy" );

    jQuery( "#noteDialog" ).dialog({
        autoOpen: false,
        height: 450,
        width: 470,
        modal: true,
        open : function() {
            var _item = jQuery(this).data('link');
            jQuery(this).find('#previewNote').draggable("disable");
            
            jQuery('#note-post').button();
            
            if (_item) {
                var _content = jQuery(_item).find('.body').text();
                var _data = jQuery(_item).find('span.data').text();
                var _author = jQuery(_item).find('.author').text();
                var _color = jQuery(_item).find('.color').text();
                var _estimate = jQuery(_item).find('.estimate').text();
                var _timeleft = jQuery(_item).find('.timeleft').text();
                jQuery('#previewNote .body').text(_content);
                jQuery('#noteData .pr-body').text(_content);
                jQuery('#previewNote .author').text(_author);
                jQuery('#noteData .pr-author').val(_author);
                jQuery('#previewNote span.data').text(_data);
                jQuery('#previewNote span.color').text(_color);

                jQuery('#previewNote span.estimate').text(_estimate);
                jQuery('#previewNote span.timeleft').text(_timeleft);
                jQuery('#noteData .pr-estimate').val(_estimate);
                jQuery('#noteData .pr-timeleft').val(_timeleft);

                jQuery('#previewNote').addClass(_color);

                jQuery('#note-post').button( "option", "disabled", false );
                
                jQuery( "#note-post" )
        				.button()
        				.click(function() {
        			location.href='?p='+_data;
    			});
                
            }
            else{
                jQuery('#previewNote .body').text('');
                jQuery('#noteData .pr-body').val('');
                jQuery('#previewNote .author').text('');
                jQuery('#noteData .pr-author').val('');
                jQuery('#previewNote span.data').text('');
                jQuery('#previewNote span.color').text('yellow');
                jQuery('#previewNote').addClass('yellow');

                jQuery('#previewNote span.estimate').text('0');
                jQuery('#previewNote span.timeleft').text('0');
                jQuery('#noteData .pr-estimate').val('0');
                jQuery('#noteData .pr-timeleft').val('0');

                jQuery('#note-post').button( "option", "disabled", true );


            }
        }
    });

    jQuery( ".add_new_note" )
        .button()
        .click(function() {
            jQuery( "#noteDialog" )
                    .data('link', false)
                    .dialog( "open" );
    });

    jQuery( "#note-close" )
        .button()
        .click(function() {
            jQuery( "#noteDialog" ).dialog( "close" );
    });

    make_editable();
                  
	/* Listening for keyup events on fields of the "Add a note" form: */
	jQuery('.pr-body,.pr-author,.pr-estimate,.pr-timeleft').live('keyup',function(e){
		if(!this.preview)
			this.preview=jQuery('#noteDialog .note');
		
		/* Setting the text of the preview to the contents of the input field, and stripping all the HTML tags: */
		this.preview.find(jQuery(this).attr('class').replace('pr-','.')).html(jQuery(this).val().replace(/<[^>]+>/ig,''));
	});
	
	/* Changing the color of the preview note: */
	jQuery('.color').live('click',function(){
		jQuery('#previewNote').removeClass('yellow green blue purple orange pink').addClass(jQuery(this).attr('class').replace('color',''));
        jQuery('#previewNote span.color').text(jQuery(this).attr('class').replace('color ',''));
   	});
	
	/* The submit button: */
	jQuery('#note-submit').live('click',function(e){
		
		if(jQuery('#noteData .pr-body').val().length<1)
		{
			alert("The note text is too short!");
			return false;
		}
		
		if(jQuery('#noteData .pr-author').val().length<1)
		{
			alert("You haven't entered your name!");
			return false;
		}
		
        var _id = jQuery('#previewNote span.data').first().text();
        
		var data = {
			action : 'hyperboard_insert_note',
			'zindex'	: ++zIndex,
			'body'		: jQuery('#noteData .pr-body').val(),
			'author'	: jQuery('#noteData .pr-author').val(),
            'board'     : jQuery('#noteData span.board').text(),
            'id'        : _id,
			'color'		: jQuery('#previewNote span.color').first().text(),
            'estimate'  : jQuery('#noteData .pr-estimate').val(),
            'timeleft'  : jQuery('#noteData .pr-timeleft').val()
		};
		
		/* Sending an AJAX POST request: */
		jQuery.post('./wp-admin/admin-ajax.php',data,function(msg){
		
			_newId = msg.replace(/.*<post>(.*?)<\/post>.*/ig, "$1");
			if(parseInt(_newId))
			{
                if (_id==_newId) {
                    //Find the old note!
                    var _old = jQuery('#hyperboard_note_'+_id);
                    _old.find('.body').text(jQuery('#noteData .pr-body').val());
                    _old.find('.author').text(jQuery('#noteData .pr-author').val());
                    _old.find('.estimate').text(jQuery('#previewNote span.estimate').text());
                    _old.find('.timeleft').text(jQuery('#previewNote span.timeleft').text());
                    _old.find('.color').text(jQuery('#previewNote span.color').text());
                    _old.removeClass('yellow green blue purple orange pink').addClass(jQuery('#previewNote span.color').text());
                    /*jQuery('#previewNote .body')*/
                }
                else {
				    /* msg contains the ID of the note, assigned by MySQL's auto increment: */
				    var tmp = jQuery('#previewNote').clone();
                    tmp.attr("id",'hyperboard_note_' + _newId);
				    tmp.find('span.data').text(_newId).end().css({'z-index':zIndex,top:72,left:42});
				    tmp.appendTo(jQuery('#hyperboardmain'));
                    make_draggable(tmp);
                }
               make_editable();
			}
		});
		e.preventDefault();
        jQuery( "#noteDialog" ).dialog( "close" );
	})

	jQuery('.note-form').live('submit',function(e){e.preventDefault();});
});

var zIndex = 0;

function make_editable()
{
    
    jQuery('.note').click(function(){
        var _item = jQuery(this);
        jQuery( "#noteDialog" )
                .data('link', jQuery(this))
                .dialog("open");
    });
}


function make_draggable(elements)
{
	/* Elements is a jquery object: */
	
	elements.draggable({
		containment:'parent',
		start:function(e,ui){ ui.helper.css('z-index',++zIndex); },
		stop:function(e,ui){
			
			/* Sending the z-index and positon of the note to update_position.php via AJAX GET: */
			jQuery.get('./wp-admin/admin-ajax.php',{
                  action : 'hyperboard_update_position',
				  x		: ui.position.left,
				  y		: ui.position.top,
				  z		: zIndex,
				  id	: parseInt(ui.helper.find('span.data').html())
			});
		}
	});
    
}